//
//  QZComplaintVc.m
//  WeiWeiHaircut
//
//  Created by 上官惠阳 on 15/12/12.
//  Copyright © 2015年 超群. All rights reserved.
//

#import "QZComplaintVc.h"
#import "QZEditUserMsgCell.h"
#import "QZKeepView.h"
#import "SQPhotosCell.h"
#import "UIViewController+tool.h"
#import "ZLPhotoPickerViewController.h"
#import "ZLPhoto.h"
#import "QZComplaintVc.h"

#define itemWidth WIDTH/4

@interface QZComplaintVc ()<UIActionSheetDelegate,ZLPhotoPickerViewControllerDelegate,ZLPhotoPickerBrowserViewControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (strong,nonatomic)NSMutableArray *collectionSource;
@property (strong,nonatomic)UICollectionView *collectionView;
@end

@implementation QZComplaintVc
{
    UIView *_grayView;
    QZKeepView *_keepView;
    UIActionSheet *sheet;
    NSIndexPath *_seleteIndexPath;
    NSMutableArray *_photosArray;
    UIImage *_addImage;//点击它添加图片
    UIView *_collectionBackView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self titleWithSting:@"投诉"];
    
    [self addBtnOnNavWithTitle:@"取消" andImageName:@"返回" andTarget:self andAction:@selector(backAction) andFrame:CGRectMake(0, 0,45, 15) andDirection:left];
    
    [self addBtnOnNavWithTitle:@"发送" andImageName:nil andTarget:self andAction:@selector(sendAction) andFrame:CGRectMake(0, 0, 40, 20) andDirection:right];
    
    [self createTableViewWithPlainStyle:YES andSeparatorStyleNone:YES andBackGroudImageName:nil];
    self.tableView.backgroundColor = BACKGROUDCOLOR;
    
    [self registCellWithNib:@"QZEditUserMsgCell" addIdentifier:@"editCell" addHeight:135];
    
    [self.tableSource addObject:@""];
    [self.tableView reloadData];
    
    [self createGrayView];
    [self createKeepView];
    
    [self createAddImageView];
}
//发送投诉
-(void)sendAction
{
    if (self.seleteTextView.text.length == 0) {
        [[iToast makeText:@"输入的内容不能为空"] show];
        return;
    }
    if(self.seleteTextView.text.length>200){
        [[iToast makeText:@"输入的投诉内容过长"]show];
        return;
    }


    
    
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"HairOrder.GetHairOrderComplain"];
    NSMutableDictionary *imageDic = [NSMutableDictionary dictionary];
    
    for (int i = 0;  i<_collectionSource.count -1 ; i++) {
        UIImage *image = _collectionSource[i];
        NSData *imageData = UIImageJPEGRepresentation(image,0.5);
        [imageDic setObject:imageData forKey:[NSString stringWithFormat:@"imaeg%d",i]];
        
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@(self.model.id) forKey:@"order_id"];
    [dic setObject:[QZUserInfo userId] forKey:@"user_id"];
    [dic setObject:self.seleteTextView.text forKey:@"content"];
    [dic setObject:@"imaeg" forKey:@"img"];

    [self.request QZRequest_Uploads_POST:url parameters:dic tagNSString:@"投诉" file:imageDic stopRequest:NO isSerializer:NO];

}
-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
//灰色图层
-(void)createGrayView
{
    UIView *grayView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    grayView.backgroundColor = [UIColor blackColor];
    grayView.alpha = 0.5;
    grayView.hidden = YES;
    [self.view addSubview:grayView];
    _grayView = grayView;
}
//发送成功后的提示视图
-(void)createKeepView
{
    _keepView = [[[NSBundle mainBundle]loadNibNamed:@"QZKeepView" owner:self options:nil]lastObject];
    _keepView.frame = CGRectMake(0, 115 + 64, WIDTH, 125);
    _keepView.hidden = YES;
    _keepView.alertContentLabel.text = @"发送成功";
    [self.view addSubview:_keepView];
}
//创建添加图片的视图
-(void)createAddImageView
{
    _photosArray = [[NSMutableArray alloc]init];
    _collectionSource = [[NSMutableArray alloc]init];
    
    [self createCollectionView];
    
    //点击它添加图片
    _addImage = [UIImage imageNamed:@"icon_addphoto"];
    [self.collectionSource addObject:_addImage];

    [self.collectionView reloadData];
    [self.tableView reloadData];
    
    [self createSheetView];
}
//创建collectionView
-(void)createCollectionView
{
    _collectionBackView = [[UIView alloc]initWithFrame:CGRectZero];
    _collectionBackView.backgroundColor = [UIColor clearColor];
    //确定是水平滚动，还是垂直滚动
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    _collectionView=[[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    _collectionView.dataSource=self;
    _collectionView.delegate=self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [_collectionView registerNib:[UINib nibWithNibName:@"SQPhotosCell" bundle:nil] forCellWithReuseIdentifier:@"phoneCell"];
    [_collectionBackView addSubview:_collectionView];
}
#pragma mark UITableViewDelegate
-(void)loadCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    QZEditUserMsgCell *editCell = (QZEditUserMsgCell *)cell;
    editCell.alertLabel.text = @"输入投诉内容，限长200字";
    self.seleteTextView  = editCell.contentTextView;
    editCell.selectionStyle = UITableViewCellSelectionStyleNone;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    CGFloat height = itemWidth * ((self.collectionSource.count - 1)/4 + 1);
    _collectionBackView.frame = CGRectMake(0, 0, WIDTH, height + 15);
    self.collectionView.frame = CGRectMake(0, 15, WIDTH,height);
    return _collectionBackView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = itemWidth * ((self.collectionSource.count - 1)/4 + 1) + 15;
    return height;
}
#pragma mark UITcollectionDelegate
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SQPhotosCell *phoneCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"phoneCell" forIndexPath:indexPath];
    phoneCell.imageView.image = self.collectionSource[indexPath.row];
    return phoneCell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.collectionSource[indexPath.row] != _addImage) {
        [self setupPhotoBrowserAtIndexPath:indexPath];
        return;
    }
    
    _seleteIndexPath = indexPath;
    [sheet showInView:self.view];
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _collectionSource.count;
}
//定义每个Item 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(itemWidth, itemWidth);
}
//纵向间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
// 行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
//创建SheetView
-(void)createSheetView
{
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
        
    }else {
        
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册", nil];
    }
    
    sheet.tag = 255;
}
#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 255) {
        
        NSUInteger sourceType = 0;
        
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            switch (buttonIndex) {
                case 0:
                    // 相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                    
                case 1:
                    // 相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                    
                case 2:
                    // 取消
                    return;
            }
        }
        else {
            if (buttonIndex == 1) {
                
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            }
        }
        // 跳转到相机或相册页面
        if(sourceType == UIImagePickerControllerSourceTypeCamera){
            [self createImagePickerControllerWithSourceType:sourceType];
        }else{
            [self selectPicture];
        }
        
    }
}
#pragma mark  ZLPhotoPickerBrowserViewController - setupCell click
- (void) setupPhotoBrowserAtIndexPath:(NSIndexPath *) indexPath{
    ZLPhotoPickerBrowserViewController *pickerBrowser = [[ZLPhotoPickerBrowserViewController alloc] init];
    pickerBrowser.hidesBottomBarWhenPushed = YES;
    pickerBrowser.delegate = self;
    [_photosArray removeAllObjects];
    for (int i = 0 ; i< self.collectionSource.count; i++) {
        ZLPhotoPickerBrowserPhoto *photo = [[ZLPhotoPickerBrowserPhoto alloc] init];
        photo.photoImage = self.collectionSource[i];
        if (self.collectionSource[i] == _addImage) {
            continue;
        }else{
            [_photosArray addObject:photo];
        }
    }
    pickerBrowser.photos = _photosArray;
    pickerBrowser.editing = YES;
    pickerBrowser.currentIndexPath = indexPath;
    [pickerBrowser showPushPickerVc:self];
}

#pragma mark ZLPhotoPickerBrowserViewControllerDelegate - 删除调用
- (void)photoBrowser:(ZLPhotoPickerBrowserViewController *)photoBrowser removePhotoAtIndexPath:(NSIndexPath *)indexPath{
    // 删除照片时调用
    [self.collectionSource removeObjectAtIndex:indexPath.row];
    if (self.collectionSource.count == 0) {
        [photoBrowser.navigationController popViewControllerAnimated:YES];
    }
    if (self.collectionSource.count < 9) {
        [self.collectionSource addObject:_addImage];
    }
    
    [self.collectionView reloadData];
    [self.tableView reloadData];
}
#pragma mark - ZLPhotoPickerViewControllerDelegate
-(void)pickerViewControllerDoneAsstes:(NSArray *)assets
{
    [self.collectionSource removeLastObject];
    
    for (int i = 0; i < assets.count ; i++) {
        UIImage *image = [assets[i] originImage];
        [self.collectionSource addObject:image];
    }
    
    if (self.collectionSource.count < 9) {
        [self.collectionSource addObject:_addImage];
    }
    
    [self.collectionView reloadData];
    [self.tableView reloadData];
}
- (void)selectPicture
{
    ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init];
    // 默认显示相册里面的内容SavePhotos
    pickerVc.status = PickerViewShowStatusSavePhotos;
    pickerVc.delegate = self;
    pickerVc.maxCount = 9 - (self.collectionSource.count - 1);
    [pickerVc showPickerVc:self];
}
#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [self.collectionSource removeLastObject];
    
    [self.collectionSource addObject:image];
    
    if (self.collectionSource.count < 9) {
        [self.collectionSource addObject:_addImage];
    }
    
    
    [self.collectionView reloadData];
    [self.tableView reloadData];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)request_Uploads_POST_FinishValue:(id)value tagNSString:(NSString *)tag{
    if ([tag isEqualToString:@"投诉"]) {
        if ([value[@"data"][@"status"] integerValue] == 100) {
            //成功
            _grayView.hidden = NO;
            _keepView.hidden = NO;
            [self performSelector:@selector(backAction) withObject:nil afterDelay:0.5];
        }else{
            //失败
            [[iToast makeText:@"投诉失败"] show];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
